import { query, mutation, baseImgUrl } from '@/utils/http'

// 通过查询已支付订单来获取用户的行程
function apiGetTravels(token, params) {
  const str = `
  ($request:OrderListRequest!){
    orderList(request:$request){
      page{
        hasNext
      }
      datas{
        rownum
        orderNumber
        travelDate
        route{
          id
          name
          picture
        }
        routeProcessStatus
      }
    }
  }
  `
  return new Promise((resolve, reject) => {
    query(token, str, { request: params })
      .then(res => {
        if (res.data.data && res.data.data.orderList) {
          const result = res.data.data.orderList
          const hasNext = result.page.hasNext
          const travels = result.datas.map(v => ({
            id: v.orderNumber,
            travelId: v.route ? v.route.id : '',
            name: v.route ? v.route.name : '',
            picture: v.route ? `${baseImgUrl}${v.route.picture}` : '',
            status: v.routeProcessStatus,
            date: v.travelDate
          }))
          const last = result.datas[0].rownum
          resolve({ travels, hasNext, last })
        } else {
          reject(new Error('has no data'))
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}

function apiSchedules(token, orderNumber) {
  const str = `
    ($orderNumber:String!){
      orderDetail(orderNumber:$orderNumber){
        route{
          schedules{
            id
            schedulePlaces{
              id
              name
              traffic
            }
            scheduleIntros{
              id
              type
              content
            }
          }
        }
      }
    }
  `
  return new Promise((resolve, reject) => {
    query(token, str, { orderNumber })
      .then(res => {
        if (res.data.data && res.data.data.orderDetail && res.data.data.orderDetail.route) {
          const result = res.data.data.orderDetail.route
          if (result.schedules && result.schedules.length) {
            const schedules = result.schedules.map(v => ({
              id: v.id,
              places: v.schedulePlaces.map(p => ({
                id: p.id,
                name: p.name,
                trafficType:
                  p.traffic === '飞机' ? 1 : p.traffic === '轮船' ? 2 : p.traffic === '汽车' ? 3 : 0
              })),
              desc: v.scheduleIntros.map(d => ({
                ...d,
                content: d.type === 'img' ? `${baseImgUrl}${d.content}` : d.content
              }))
            }))
            resolve(schedules)
          }
        } else {
          reject(new Error('has no route'))
        }
      })
      .catch(err => reject(err))
  })
}

export { apiGetTravels, apiSchedules }
